package com.campus.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.api.util.UserContext;
import com.campus.common.result.Result;
import com.campus.common.student.job.entity.Student;
import com.campus.common.student.mapper.StudentMapper;
import com.campus.common.teacher.job.entity.Teacher;
import com.campus.common.teacher.mapper.TeacherMapper;
import com.campus.common.user.entity.pojo.User;
import com.campus.common.user.mapper.AuthMapper;
import com.campus.course.dto.entity.CourseRecords;
import com.campus.course.dto.entity.CourseSchedule;
import com.campus.course.dto.entity.Courses;
import com.campus.course.dto.form.UpdateCourseForm;
import com.campus.course.dto.vo.CourseListVO;
import com.campus.course.dto.vo.StuCoursesVo;
import com.campus.course.mapper.CourseRecordsMapper;
import com.campus.course.mapper.CourseScheduleMapper;
import com.campus.course.mapper.CoursesMapper;
import com.campus.course.service.ICoursesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author maojr
 * @since 2024-11-16
 */
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> implements ICoursesService {

    @Autowired
    private CourseScheduleMapper courseScheduleMapper;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private CourseRecordsMapper courseRecordsMapper;

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private TeacherMapper teacherMapper;



    @Override
    public List<CourseListVO> selectAllCourses () {
        List<Courses> courseList = coursesMapper.selectList(null);
        List<CourseListVO> list = new ArrayList<>();
        courseList.forEach(course -> {
            Teacher teacher = teacherMapper.selectById(course.getTeacherId());
            User user = authMapper.selectById(teacher.getUserId());
            CourseListVO vo = new CourseListVO();
            BeanUtils.copyProperties(course, vo);
            vo.setTeacherName(user.getName());

            list.add(vo);
        });
        return list;
    }

    @Override
    public Result searchCourse(String keyWords) {
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("course_name", keyWords);
        List<Courses> courses = coursesMapper.selectList(queryWrapper);
        return Result.success(courses,null);
    }

    @Override
    public Result addCourse(Courses course) {
        if (coursesMapper.insert(course) > 0) {
            return Result.success("新增课程成功");
        }
        else {
            return Result.fail("新增课程失败");
        }
    }

    @Override
    public Result updateCourse(UpdateCourseForm updateCourseForm) {

        if (updateCourseForm.getRemain() < 0 || updateCourseForm.getRemain() > 160) {
            return Result.fail("修改课程失败,不合理的容量");
        }
        if (updateCourseForm.getStudyScore() < 0 || updateCourseForm.getStudyScore() > 50) {
            return Result.fail("修改课程失败,学分超过规定限制");
        }
        Courses course = coursesMapper.selectById(updateCourseForm.getId());
        BeanUtils.copyProperties(updateCourseForm, course);

        if (coursesMapper.updateById(course) > 0) {
            return Result.success("修改课程成功");
        }
        else {
            return Result.fail("修改课程失败");
        }
    }

    @Override
    public Result deleteCourse(int courseId) {
        //判断该课程是否还有排课
        if (!courseScheduleMapper.selectList(new QueryWrapper<CourseSchedule>().eq("course_id", courseId)).isEmpty()) {
            return Result.fail("删除课程失败，该课程存在排课");
        }

        if (coursesMapper.deleteById(courseId) > 0) {
            return Result.success("删除课程成功");
        }
        else {
            return Result.fail("删除课程失败");
        }
    }

    @Override
    public Result getStuCourse() {
        int userId = UserContext.getUserId();
        //获取学生学号(id)
        Student student = studentMapper.selectOne(
                new QueryWrapper<Student>().eq("user_id", userId)
        );
        System.out.println("学生"+student.toString());
        //获取学生选课记录
        List<CourseRecords> records = courseRecordsMapper.selectList(
                new QueryWrapper<CourseRecords>().eq("student_id",student.getId())
        );
        System.out.println("选课"+records.toString());
        List<StuCoursesVo> stuCoursesVos = new ArrayList<>();
        //获取学生所选课程信息
        for (CourseRecords record : records) {
            Courses course =coursesMapper.selectById(record.getCourseId());
            //装载信息
            StuCoursesVo stuCoursesVo = new StuCoursesVo();
            stuCoursesVo.setCourseName(course.getCourseName());
            stuCoursesVo.setCourseId(course.getId());
            stuCoursesVo.setStudyScore(course.getStudyScore());
            stuCoursesVo.setTeacherName(authMapper.selectById(teacherMapper.selectById(course.getTeacherId()).getUserId()).getName());
            //添加到返回列表
            stuCoursesVos.add(stuCoursesVo);
        }

        return Result.success(stuCoursesVos,"学生选课返回.");
    }

    @Override
    public Result teacherGetCourses() {
        int userId = UserContext.getUserId();
        Teacher teacher = teacherMapper.selectOne(
                new QueryWrapper<Teacher>().eq("user_id", userId)
        );
        List<Courses> courses = coursesMapper.selectList(new QueryWrapper<Courses>().eq("teacher_id",teacher.getId()));
        return Result.success(courses,null);
    }


}
